package com.iflytek.uoamp.agent.monitor.find.imp.baseitem;

import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.Program;
import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.ProgramType;
import com.iflytek.uoamp.agent.monitor.find.obj.NetWork;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentConfig;

import org.apache.log4j.Logger;
import org.hyperic.sigar.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class FindWinBaseMonitorItem extends FindBaseMonitorItemAbs {
	public static DecimalFormat df = new DecimalFormat("######0.00");

	public FindWinBaseMonitorItem(String path) {
		super(path);
	}

	@Override
	protected List<Program> getDisks() {
		List<Program> results = new LinkedList<Program>();
		// 获取磁盘列表信息
		File[] roots = File.listRoots();
		for (File file : roots) {
			Program cprogram = new Program();
			List<String> flags = new LinkedList<String>();
			cprogram.setCpname("win_disk_" + diskPathFilter(file.getPath()));
			cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
			cprogram.setType(ProgramType.BASE);
			cprogram.setFlags(flags);
			cprogram.setPath(diskPathFilter(file.getPath()));
			// get主机名称
			cprogram.setHostname(MCAgentConfig.getInstance().getMonitoredHostName());
			results.add(cprogram);
		}

		return results;
	}

	@Override
	protected List<Program> getCPU() {
		List<Program> list = new LinkedList<Program>();
		Sigar sigar = new Sigar();
		CpuInfo infos[];
		try {
			infos = sigar.getCpuInfoList();
			for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用
				Program cprogram = new Program();
				cprogram.setCpname("win_cpu");
				cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
				cprogram.setType(ProgramType.BASE);
				List<String> flags = new LinkedList<String>();
				flags.add(i + "");
				cprogram.setFlags(flags);
				cprogram.setPort(i);
				list.add(cprogram);
			}
		} catch (SigarException e) {
			Logger.getRootLogger().error("获取基础cpu信息失败！" + e.toString());
		}

		Program cprogram = new Program();
		cprogram.setCpname("win_cpu");
		cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
		cprogram.setType(ProgramType.BASE);
		List<String> flags = new LinkedList<String>();
		flags.add("all");
		cprogram.setFlags(flags);
		cprogram.setPort(100);
		list.add(cprogram);
		return list;
	}

	@Override
	protected Program getMemory() {
		Program cprogram = new Program();
		cprogram.setCpname("win_mem");
		cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
		cprogram.setType(ProgramType.BASE);
		List<String> flags = new LinkedList<String>();
		cprogram.setFlags(flags);
		return cprogram;
	}

	@Override
	protected List<Program> getDiskIO() {

		List<Program> results = new LinkedList<Program>();

		// 获取磁盘列表信息
		File[] roots = File.listRoots();
		for (File file : roots) {
			Program cprogram = new Program();
			List<String> flags = new LinkedList<String>();
			cprogram.setCpname("win_diskio_" + diskPathFilter(file.getPath()));
			cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
			cprogram.setType(ProgramType.BASE);
			cprogram.setFlags(flags);
			cprogram.setPath(diskPathFilter(file.getPath()));
			// get主机名称
			cprogram.setHostname(MCAgentConfig.getInstance().getMonitoredHostName());
			results.add(cprogram);
		}
		return results;
	}

	@Override
	protected Program getInterface() {
		String ip = MCAgentConfig.getInstance().getMonitoredPointIp();
		Logger.getRootLogger().info("get network ip =======================================> " + ip);

		if (ip == null || ip.isEmpty()) {
			return null;
		}

		Sigar sigar = new Sigar();
		LinkedList<NetWork> network = new LinkedList<NetWork>();
		// 获取网络流量等信息
		try {
			String[] ifNames = sigar.getNetInterfaceList();
			Logger.getRootLogger().info("!IFF_UP...skipping getNetInterfaceStat" + ifNames.length);
			for (int i = 0; i < ifNames.length; i++) {
				String name = ifNames[i];
				NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);

				if ((ifconfig.getFlags() & 1L) <= 0L) {
					Logger.getRootLogger().info("!IFF_UP...skipping getNetInterfaceStat");
					continue;
				}

				NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);

				if (ip.equals(ifconfig.getAddress())) {
					NetWork curnet = new NetWork();
					curnet.setName(name);
					curnet.setIp(ifconfig.getAddress());
					curnet.setTransportByte(ifstat.getRxBytes() + "");

					network.add(curnet);
				}
			}
		} catch (SigarException e) {
			Logger.getRootLogger().info("get network ip exception ", e);
		}

		NetWork netWork = null;
		for (NetWork cur : network) {
			// 如果没有 IP 则跳过;
			if (cur.getIp() != null && cur.getIp().equals(ip)) {
				netWork = cur;
				break;
			}
		}

		if (netWork == null)
			return null;

		Program cprogram = new Program();
		cprogram.setCpname("win_interface");
		cprogram.setIp(ip);
		cprogram.setType(ProgramType.BASE);
		List<String> flags = new LinkedList<String>();
		flags.add(netWork.getName());
		cprogram.setFlags(flags);
		// get主机名称
		cprogram.setHostname(MCAgentConfig.getInstance().getMonitoredHostName());
		return cprogram;
	}

	/**
	 * wlhu, 2014/10/27, 过滤磁盘路径信息 C:\\，获取盘符信息
	 * 
	 * @param rootInfo
	 * @return
	 */
	private static String diskPathFilter(String rootInfo) {
		return rootInfo.substring(0, rootInfo.length() - 2);
	}

	/**
	 * 获取 cpu 具体信息
	 * */
	@Override
	protected Program getCPUInfo() {
		Sigar sigar = new Sigar();
		Map<String, String> cupInfo = new HashMap<String, String>();
		try {
			CpuInfo[] cpuInfos = sigar.getCpuInfoList();
			if (cpuInfos.length > 0) {
				List<String> cpu = new ArrayList<String>();
				for (CpuInfo cpuInfo : cpuInfos) {
					String cpuMdle = cpuInfo.getModel();
					if (!cpu.contains(cpuMdle)) {
						cpu.add(cpuMdle);
					}
				}
				cupInfo.put("cpuNum", cpu.size() + "");
				cupInfo.put("Mhz", df.format((double) cpuInfos[0].getMhz() / 1024) + "");
				cupInfo.put("Cores", cpuInfos.length + "");
			}

		} catch (SigarException e) {
			Logger.getRootLogger().info("windows getCPUInfo fail!", e);
		}

		Program cprogram = new Program();
		cprogram.setCpname("cpuInfo");
		cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
		cprogram.setType(ProgramType.INFO);
		cprogram.setHeaders(cupInfo);
		return cprogram;
	}

	/**
	 * 内存监控项具体信息
	 * */
	@Override
	protected Program getMemoryInfo() {
		Sigar sigar = new Sigar();
		Map<String, String> memoryInfo = new HashMap<String, String>();
		try {
			Mem mem = sigar.getMem();
			memoryInfo.put("totalMemory", (mem.getTotal() / 1024L / 1024L / 1024L + 1) + "");
		} catch (SigarException e) {
			Logger.getRootLogger().info("windows getMemoryInfo fail!", e);
		}

		Program cprogram = new Program();
		cprogram.setCpname("memoryInfo");
		cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
		cprogram.setType(ProgramType.INFO);
		cprogram.setHeaders(memoryInfo);
		return cprogram;
	}

	/**
	 * 操作系统具体信息
	 * */
	@Override
	protected Program getOsInfo() {
		OperatingSystem operatingSystem = OperatingSystem.getInstance();
		Map<String, String> oSInfo = new HashMap<String, String>();
		String systemName = "windows 7";
		if (operatingSystem.getVersion().equals("6.3")) {
			systemName = "windows 10";
		} else if (operatingSystem.getVersion().equals("6.2")) {
			systemName = "windows 8";
		} else {
			systemName = operatingSystem.getVendorName();
		}
		oSInfo.put("systemInfo", systemName);
		Program cprogram = new Program();
		cprogram.setCpname("systemInfo");
		cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
		cprogram.setType(ProgramType.INFO);
		cprogram.setHeaders(oSInfo);
		return cprogram;
	}

	/**
	 * 操作系统JDK版本具体信息
	 * */

	@Override
	protected Program getJdkVersion() {
		String jdkVersion = System.getProperty("java.version");
		Map<String, String> jdkInfo = new HashMap<String, String>();
		jdkInfo.put("jdkVersion", jdkVersion);
		Program cprogram = new Program();
		cprogram.setCpname("jdkVersion");
		cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
		cprogram.setType(ProgramType.INFO);
		cprogram.setHeaders(jdkInfo);
		return cprogram;
	}

	/***
	 * 获取系统运行时间
	 * 
	 */
	@Override
	protected Program getRunTime() {
		Process process;
		String startUpTime = "";
		String currentTime = "";
		String runTime = " ";
		InputStreamReader isr = null;
		BufferedReader bufferedReader = null;
		try {
			process = Runtime.getRuntime().exec("cmd /c net statistics workstation");
		    isr = new InputStreamReader(process.getInputStream(), "gbk");
			bufferedReader = new BufferedReader(isr);
			int i = 0;
			String timeWith = "";
			while ((timeWith = bufferedReader.readLine()) != null) {
				if (i == 3) {
					startUpTime = timeWith;
				}
				i++;
			}
			process.waitFor();
			String[] str = startUpTime.split(" ");
			startUpTime = str[1] + " " + str[2];
			SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 设置日期格式
			currentTime = df.format(new Date());// new Date()为获取当前系统时间

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			java.util.Date now = sdf.parse(currentTime);
			java.util.Date date = sdf.parse(startUpTime);
			long l = now.getTime() - date.getTime();
			long day = l / (24 * 60 * 60 * 1000);
			long hour = (l / (60 * 60 * 1000) - day * 24);
			long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
			// long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min *
			// 60);
			runTime = day + "天" + hour + "小时" + min + "分";
		} catch (IOException e) {
			Logger.getRootLogger().error("run command fail! The IOException is ：" + e);
		} catch (InterruptedException e) {
			Logger.getRootLogger().error("run command fail! The InterruptedException is ：" + e);
		} catch (ParseException e) {
			Logger.getRootLogger().error("run command fail! The ParseException is ：" + e);
		} finally {
			if(isr != null){
				try {
					isr.close();
				} catch (IOException e) {
					Logger.getRootLogger().error("close isr fail! The Exception is ：" + e);
				}
			}
			
			if(bufferedReader != null){
				try {
					bufferedReader.close();
				} catch (IOException e) {
					Logger.getRootLogger().error("close bufferedReader fail! The Exception is ：" + e);
				}
			}
		}
		Map<String, String> runTimeInfo = new HashMap<String, String>();
		runTimeInfo.put("runTimeInfo", runTime);
		Program cprogram = new Program();
		cprogram.setCpname("runTimeInfo");
		cprogram.setIp(MCAgentConfig.getInstance().getMonitoredPointIp());
		cprogram.setType(ProgramType.INFO);
		cprogram.setHeaders(runTimeInfo);
		return cprogram;
	}
}
